package com.sky.zzh.today;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.utils.ValueFormatter;
import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.zzh.R;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;

/**
 * 今日数据
 * 
 * @author steveyan
 *
 */
public class GetUpFragment extends IFragment implements ITaskListener {

  // 常量
  private static final String PARAM_STARTHOUR = "param1";
  private static final String PARAM_ENDHOUR = "param2";
  private static final String PARAM_STARTDATE = "param3";
  private static final String PARAM_ENDDATE = "param4";
  private static final String PARAM_ISDEFAULT = "param5";



  // 接收的参数
  private int type;
  private String date;

  // fragment和activity的通信接口
  private OnFragmentInteractionListener mListener = null;
  private BarChart barChart;

  // X轴显示的内容
  private ArrayList<String> xVals;

  public GetUpFragment() {}


  private SHGet getUpTask;
  private String today = "20150924";
  private String currentSelectDate = "20150924";
  private String fromDate = "20150926", endDate = "20150927";
  private Calendar calendar;
  private int startHour, endHour;
  private boolean isDefault = true;
  MyValueFormatter customValueFormatter;
  MyYValueFormatter mMyYValueFormatter = new MyYValueFormatter();

  //
  public static GetUpFragment newInstance(int startHour, int endHour, String startDate,
      String endDate, boolean isDefault) {
    GetUpFragment fragment = new GetUpFragment();
    Bundle args = new Bundle();
    args.putInt(PARAM_STARTHOUR, startHour);
    args.putInt(PARAM_ENDHOUR, endHour);
    args.putString(PARAM_STARTDATE, startDate);
    args.putString(PARAM_ENDDATE, endDate);
    args.putBoolean(PARAM_ISDEFAULT, isDefault);
    fragment.setArguments(args);
    return fragment;
  }



  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startHour = 6;
    endHour = 4;
    if (getArguments() != null) {
      startHour = getArguments().getInt(PARAM_STARTHOUR);
      endHour = getArguments().getInt(PARAM_ENDHOUR);
      fromDate = getArguments().getString(PARAM_STARTDATE);
      endDate = getArguments().getString(PARAM_ENDDATE);
      isDefault = getArguments().getBoolean(PARAM_ISDEFAULT);
    }
    // 获得当天的日期
    calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH) + 1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    today = year + "" + CommonUtil.getDoubleNum(month) + "" + CommonUtil.getDoubleNum(day);
    currentSelectDate = endDate;
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmen_getup, container, false);
    barChart = (BarChart) view.findViewById(R.id.chartGetUp);
    barChart.setDrawBarShadow(false);
    barChart.setDrawValueAboveBar(true);
    barChart.setDescription("");
    barChart.setPinchZoom(false);
    barChart.setDrawGridBackground(false);
    barChart.setTouchEnabled(false);
    barChart.animateY(2500);



    // 设置周边的指示
    XAxis xAxis = barChart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setDrawGridLines(false);
    xAxis.setSpaceBetweenLabels(2);
    xAxis.setTextColor(getActivity().getResources().getColor(R.color.color_charttextcolor));

    YAxis leftAxis = barChart.getAxisLeft();
    // leftAxis.setLabelCount(8, false);
    // leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
    // leftAxis.setSpaceTop(15f);

    // 左边的
    leftAxis.setEnabled(true);
    customValueFormatter = new MyValueFormatter(leftAxis);
    leftAxis.setValueFormatter(customValueFormatter);
    leftAxis.setDrawGridLines(false);
    leftAxis.setShowOnlyMinMax(true);
    leftAxis.setTextColor(getActivity().getResources().getColor(R.color.color_charttextcolor));



    YAxis rightAxis = barChart.getAxisRight();
    // rightAxis.setDrawGridLines(false);
    // rightAxis.setLabelCount(8, false);
    // rightAxis.setSpaceTop(15f);

    // 关闭右边的指示
    rightAxis.setEnabled(false);


    // 设置示例图标
    // Legend l = barChart.getLegend();
    // l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
    // l.setForm(Legend.LegendForm.SQUARE);
    // l.setFormSize(9f);
    // l.setTextSize(11f);
    // l.setXEntrySpace(4f);
    //

    // 关闭示例图标
    barChart.getLegend().setEnabled(false);


    requestData(fromDate, endDate);

    return view;
  }

  private void requestData(String fromDate, String endDate) {
    SHDialog.dismissProgressDiaolg();
    if (getUpTask != null) {
      getUpTask.cancel(true);
    }
    SHDialog.ShowProgressDiaolg(getActivity());
    getUpTask = new SHGet();
    getUpTask.setListener(this);
    if (currentSelectDate.equals(today)) {
      getUpTask.setUrl(ConfigDefinition.URL + "app/SensorDataToday");
      getUpTask.getTaskArgs().put("UUID", UserInfoManager.getInstance().getUUID());
      // getUpTask.getTaskArgs().put("UUID", "MT003");
      getUpTask.getTaskArgs().put("UserId", UserInfoManager.getInstance().getUserId());
      getUpTask.getTaskArgs().put("DataProperty", "2");
    } else {
      StringBuffer sb = new StringBuffer();
      sb.append(ConfigDefinition.URL);
      sb.append("app/SensorDataHistory?UUID=");
      sb.append(UserInfoManager.getInstance().getUUID());
      // sb.append("MT003");
      sb.append("&");
      sb.append("DataProperty=2&FromDate=");
      sb.append(fromDate);
      sb.append("&");
      sb.append("EndDate=");
      sb.append(endDate);
      getUpTask.setUrl(sb.toString());
      // turnUpTask.setUrl(ConfigDefinition.URL + "app/SensorDataHistory");
      // turnUpTask.getTaskArgs().put("UUID", UserInfoManager.getInstance().getUUID());
      // turnUpTask.getTaskArgs().put("UUID", "MT003");
      // turnUpTask.getTaskArgs().put("UserId", UserInfoManager.getInstance().getUserId());
      // turnUpTask.getTaskArgs().put("DataProperty", "1");
      // turnUpTask.getTaskArgs().put("FromDate", fromDate);
      // turnUpTask.getTaskArgs().put("EndDate", endDate);
      // turnUpTask.getTaskArgs().put("FromTime", URLEncoder.encode("06:00"));
      // turnUpTask.getTaskArgs().put("EndTime", URLEncoder.encode("18:00"));
    }
    getUpTask.start();
  }

  private int getHourFromTime(String s) {
    String[] split = s.split(" ");
    String[] split2 = split[1].split(":");
    return Integer.valueOf(split2[0]) % 12;
  }

  private void setData() {
    xVals = new ArrayList<String>();
    List<BarEntry> yVals1 = new ArrayList<BarEntry>();
    int value = 0;
    if (endHour > startHour) {
      for (int i = startHour, j = 0; i <= endHour; i += 1, j++) {
        xVals.add(i + "");
        if (allAvailableData.containsKey(i)) {
          value = allAvailableData.get(i);
        } else {
          value = 0;
        }
        yVals1.add(new BarEntry(value, j));
      }
    } else {
      int j = 0;
      for (int i = startHour; i <= 24; i += 1, j++) {
        xVals.add(i + "");
        if (allAvailableData.containsKey(i)) {
          value = allAvailableData.get(i);
        } else {
          value = 0;
        }
        yVals1.add(new BarEntry(value, j));
      }
      for (int i = 1; i <= endHour; i += 1, j++) {
        xVals.add(i + "");
        if (allAvailableData.containsKey(i)) {
          value = allAvailableData.get(i);
        } else {
          value = 0;
        }
        yVals1.add(new BarEntry(value, j));
      }
    }

    BarDataSet set1 = new BarDataSet(yVals1, "DataSet");
    set1.setBarSpacePercent(80f);
    set1.setValueTextColor(Color.parseColor("#1dd98d"));
    set1.setValueFormatter(mMyYValueFormatter);

    ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
    dataSets.add(set1);

    BarData data = new BarData(xVals, dataSets);
    data.setValueTextSize(0f);
    barChart.clear();
    barChart.setData(data);
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
  }


  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
      mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString()
          + " must implement OnFragmentInteractionListener");
    }
  }

  @Override
  public void onDetach() {
    super.onDetach();
    mListener = null;
  }


  private HashMap<Integer, Integer> allAvailableData = new HashMap<Integer, Integer>();

  @Override
  public void onTaskFinished(SHTask task) throws Exception {
    SHDialog.dismissProgressDiaolg();
    JSONObject json = new JSONObject(task.getResult().toString());
    System.out.println("json:" + json);
    if (task == getUpTask) {
      try {
        if ("200".equals(json.optString("ReturnCode"))) {
          try {
            // 传感器的数据
            JSONArray sensorDataJSONArray = json.optJSONArray("SensorData");
            JSONArray array = null;
            JSONObject obj = null;
            // 处理property为2的体动
            for (int i = 0; i < sensorDataJSONArray.length(); i++) {
              array = sensorDataJSONArray.getJSONObject(i).optJSONArray("Data");
              int property = sensorDataJSONArray.getJSONObject(i).optInt("PropertyCode");
              if (property != 2) {
                continue;
              }
              for (int j = 0; j < array.length(); j++) {
                obj = array.getJSONObject(j);
                int index = getHourFromTime(obj.optString("At"));
                int value = obj.optInt("Value");
                if (allAvailableData.containsKey(index)) {
                  value += allAvailableData.get(index);
                }
                allAvailableData.put(index, value);
              }
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        setData();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  @Override
  public void onTaskFailed(SHTask task) {}

  @Override
  public void onTaskUpdateProgress(SHTask task, int count, int total) {}

  @Override
  public void onTaskTry(SHTask task) {}

  @Override
  void onDateChanged(String startDate, String endDate) {

  }

}
